package com.wr.online.test.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.wr.online.test.exception.GlobalException;
import com.wr.online.test.mapper.AnswerMapper;
import com.wr.online.test.mapper.PaperMapper;
import com.wr.online.test.mapper.SubjectMapper;
import com.wr.online.test.mapper.UserAnswerMapper;
import com.wr.online.test.model.entity.*;
import com.wr.online.test.model.vo.*;
import com.wr.online.test.service.IUserAnswerService;
import com.wr.online.test.validator.ValidationGroups;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.util.unit.DataUnit;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ：GZHU_WANG
 * @date ：Created in 2021/10/27 13:13
 * @description：试题接口
 */
@RestController
@RequestMapping("/paper")
@Slf4j
public class PaperController {
    @Autowired
    private IUserAnswerService userAnswerService;
    @Autowired
    private AnswerMapper answerMapper;
    @Autowired
    private PaperMapper paperMapper;
    @Autowired
    private SubjectMapper subjectMapper;


    @GetMapping("/details/{id}")
    public RespBean getDetails(@PathVariable Integer id) {
        Paper paper = paperMapper.selectJoinOne(Paper.class, new MPJQueryWrapper<Paper>().selectAll(Paper.class).eq("paper_id", id).eq("state", 0));
        if (paper == null) throw new GlobalException(RespBeanEnum.PAPER_NOT_FOUND);

        if (paper.getStartTime() == null) {
            Date date = new Date();
            boolean b = date.compareTo(paper.getOpenTime()) > 0;
            if (b) {
                b = date.compareTo(paper.getCloseTime()) < 0;
                if (b) {
                    paper.setStartTime(date);
                    paperMapper.updateById(paper);
                } else {
                    //试卷已被提交
                    throw new GlobalException(RespBeanEnum.PAPER_HAS_BEEN_OVERDUE);
                }
            } else {
                throw new GlobalException(RespBeanEnum.EARLY_TIME);
            }

        }

        PaperDetailsVo pdv = new PaperDetailsVo();
        BeanUtils.copyProperties(paper, pdv);
        pdv.setSubjects(new ArrayList<>());
        List<SubjectDetailsVO> subjects = pdv.getSubjects();
        List<Subject> subjects1 = subjectMapper.selectJoinList(Subject.class, new MPJQueryWrapper<Subject>()
                .selectAll(Subject.class)
                .inSql("t.subject_id", "select b.subject_id from user_answer b where b.paper_id =" + id)
                .orderByAsc("t.type", "t.type")
        );
        for (Subject subject : subjects1) {
            SubjectDetailsVO sdv = new SubjectDetailsVO();
            BeanUtils.copyProperties(subject, sdv);
            List<Answer> answers = answerMapper.selectJoinList(Answer.class, new MPJQueryWrapper<Answer>()
                    .selectAll(Answer.class)
                    .selectIgnore("t.type")
                    .inSql("t.answer_id", "select b.answer_id from subject_answer b where b.subject_id = " + subject.getSubjectId())
            );
            sdv.setOptions(answers);
            subjects.add(sdv);

            UserAnswer answer = userAnswerService.selectJoinOne(UserAnswer.class, new MPJLambdaWrapper<UserAnswer>()
                    .selectAll(UserAnswer.class)
                    .eq(UserAnswer::getPaperId, id).eq(UserAnswer::getSubjectId, subject.getSubjectId()));
            if (ObjectUtils.isEmpty(answer.getUserAnswer()))
                sdv.setUserAnswer(null);
            else
                sdv.setUserAnswer(answer.getUserAnswer());
            sdv.setOther(answer.getOther());
        }

        return RespBean.success(pdv);
    }


//    @PostMapping("/details/{id}")
//    public RespBean postDetails(@Validated({ValidationGroups.Update.class}) AnswerDetailsVO answerDetailsVO, @PathVariable Integer id){
//
//        @Valid List<UserAnswerVO> subjectsDetails = answerDetailsVO.getSubjectsDetails();
//
//        System.out.println(subjectsDetails);
//
//
//        return RespBean.success(subjectsDetails);
//    }

    //    @PostMapping("/details/{paperId}/{subjectId}")
    @PostMapping("/details/{id}")
    public RespBean postFile(@RequestPart(name = "file", required = false) MultipartFile[] file,
                             @Validated({ValidationGroups.Update.class}) @RequestPart("data") AnswerDetailsVO data,
                             @RequestPart(name = "index", required = false) List<Integer> index, @PathVariable Integer id) {
        if (file != null) {
            for (MultipartFile multipartFile : file) {
                System.out.println(multipartFile);
            }
            for (Integer integer : index) {
                System.out.println(integer);
            }
        }
//        System.out.println(file);
        System.out.println(data);
        return RespBean.success();
    }


    @PostMapping("/details/test/{id}/{type}")
    public RespBean postTest(@PathVariable Integer id, @Validated({ValidationGroups.Update.class}) @RequestBody AnswerDetailsVO paths, @PathVariable Integer type) {

        Paper paper = paperMapper.selectById(id);
        if(null == paper || paper.getState() != 0) throw new GlobalException(RespBeanEnum.PAPER_NOT_FOUND);
        @Valid List<UserAnswerVO> subjectsDetails = paths.getSubjectsDetails();
        List<UserAnswer> saves = new ArrayList<>();
        for (UserAnswerVO subjectsDetail : subjectsDetails) {
            UserAnswer u = new UserAnswer();
            BeanUtils.copyProperties(subjectsDetail, u);
            saves.add(u);
        }

        for (UserAnswer save : saves) {
            userAnswerService.update(save, new LambdaUpdateWrapper<UserAnswer>()
                    .eq(UserAnswer::getPaperId, save.getPaperId())
                    .eq(UserAnswer::getSubjectId, save.getSubjectId())
            );
        }
        if(type == 1)
            paperMapper.changeState(id, 1);
        return RespBean.success(paths);
    }

    @GetMapping("/details/{page}/{size}")
    public RespBean getLDetailsList(@PathVariable Integer page, @PathVariable Integer size) {

        IPage<Paper> data = paperMapper.selectJoinPage(new Page<>(page, size), Paper.class, new MPJLambdaWrapper<>().
                selectAll(Paper.class).eq(Paper::getState, 1));
//        Page<Paper> paperPage = paperMapper.selectPage(new Page<>(page, size), new LambdaQueryWrapper<Paper>()
//                .eq(Paper::getState, 1).orderByAsc(Paper::getEndTime));
//        paperMapper.selectList(new LambdaQueryWrapper<Paper>().eq(Paper::getState, 1).orderByAsc(Paper::getEndTime))
        return RespBean.success(data);
    }


    @GetMapping("/details/test/{id}")
    public RespBean getTest(@PathVariable Integer id) {

//        List<UserAnswer> userAnswers = userAnswerService.selectJoinList(UserAnswer.class, new MPJLambdaWrapper<UserAnswer>()
//                .selectAll(UserAnswer.class)
//                .eq(UserAnswer::getPaperId, id)
//        );
        Paper paper = paperMapper.selectJoinOne(Paper.class, new MPJQueryWrapper<Paper>().selectAll(Paper.class).eq("paper_id", id).eq("state", 1));
        if (paper == null) throw new RuntimeException("找不到页面");
        PaperDetailsVo pdv = new PaperDetailsVo();
        BeanUtils.copyProperties(paper, pdv);
        pdv.setSubjects(new ArrayList<>());
        List<SubjectDetailsVO> subjects = pdv.getSubjects();
        List<Subject> subjects1 = subjectMapper.selectJoinList(Subject.class, new MPJQueryWrapper<Subject>()
                .selectAll(Subject.class)
                .inSql("t.subject_id", "select b.subject_id from user_answer b where b.paper_id =" + id)
                .orderByAsc("t.type", "t.type")
        );
        for (Subject subject : subjects1) {
            SubjectDetailsVO sdv = new SubjectDetailsVO();
            BeanUtils.copyProperties(subject, sdv);
            List<Answer> answers = answerMapper.selectJoinList(Answer.class, new MPJQueryWrapper<Answer>()
                    .selectAll(Answer.class)
                    .selectIgnore("t.type")
                    .inSql("t.answer_id", "select b.answer_id from subject_answer b where b.subject_id = " + subject.getSubjectId())
            );
            sdv.setOptions(answers);
            subjects.add(sdv);

            UserAnswer answer = userAnswerService.selectJoinOne(UserAnswer.class, new MPJLambdaWrapper<UserAnswer>()
                    .selectAll(UserAnswer.class)
                    .eq(UserAnswer::getPaperId, id).eq(UserAnswer::getSubjectId, subject.getSubjectId()));
            if (ObjectUtils.isEmpty(answer.getUserAnswer()))
                sdv.setUserAnswer(null);
            else
                sdv.setUserAnswer(answer.getUserAnswer());
            sdv.setOther(answer.getOther());
        }

        return RespBean.success(pdv);
    }

    

}
